package com.aidex.biz.controller;

import com.aidex.biz.domain.BusinessSet;
import com.aidex.biz.domain.Customer;
import com.aidex.biz.domain.CustomerDongtai;
import com.aidex.biz.domain.CustomerXiezu;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.domain.vo.CustomerExpertVo;
import com.aidex.biz.domain.vo.GuanggaoChengBen;
import com.aidex.biz.domain.vo.YuanGongGongziVo;
import com.aidex.biz.service.BusinessSetService;
import com.aidex.biz.service.CustomerDongtaiService;
import com.aidex.biz.service.CustomerService;
import com.aidex.biz.service.CustomerXiezuService;
import com.aidex.biz.utils.RongXiangKeAESUtil;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.http.HttpUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.aidex.common.utils.sign.Md5Utils;
import com.aidex.framework.websocket.WebSocketServer;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.service.ISysUserService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 左心房客户推送信息Controller
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-04-03
 */
@RestController
@RequestMapping("/biz/bizCustomer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private CustomerXiezuService customerXiezuService;

    @Autowired
    private BusinessSetService businessSetService;

    /**
     * 查询左心房客户推送信息列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:list')")
    @GetMapping("/list")
    public R<PageInfo> list(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findPage(customer));
    }
    @GetMapping("/yslist")
    public R<PageInfo> yslist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.ysfindPage(customer));
    }
    @GetMapping("/alllist")
    public R<PageInfo> alllist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            if(!StringUtils.isEmpty(SecurityUtils.getLoginUser().getUser().getCity())){
                String cityName=SecurityUtils.getLoginUser().getUser().getCity();
                String[] cityNames=cityName.replace("[","").replace("\"","").replace("]","").replace("市","").replace("省",
                        " ").split(",");
                customer.setCityNames(cityNames);
                customer.setIsCity("1");
            }else{
                customer.setCityName("0");
            }
        }
        return R.data(customerService.findAllList(customer));
    }



    @GetMapping("/xiansuochilist")
    public R<PageInfo> xiansuochilist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            customer.setUserId(SecurityUtils.getUserId());
        }

        return R.data(customerService.findPage(customer));
    }

    @GetMapping("/teamxiansuochilist")
    public R<PageInfo> teamxiansuochilist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findPage(customer));
    }


    @GetMapping("/mylist")
    public R<PageInfo> mylist(Customer customer, HttpServletRequest request, HttpServletResponse response) {

        customer.setPage(new PageDomain(request, response));

        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            customer.setUserId(SecurityUtils.getUserId());
        }

        return R.data(customerService.findMyList(customer));
    }

    @GetMapping("/chenjiaolist")
    public R<PageInfo> chenjiaolist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
//        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())&&!SecurityUtils.isSysAdmin(SecurityUtils.getUserId())){
//            customer.setUserId(SecurityUtils.getUserId());
//        }
        return R.data(customerService.findChengJiaoList(customer));
    }




    @GetMapping("/gonghailist")
    public R<PageInfo> gonghailist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if(StringUtils.isEmpty(customer.getCompanyId())){
            customer.setCompanyId(null);
        }
        return R.data(customerService.findgonghaiList(customer));
    }



    @GetMapping("/xieZuList")
    public R<PageInfo> xieZuList(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findListXieZu(customer));
    }

    /**
     * 获取左心房客户推送信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:query')")
    @GetMapping(value = "/{id}")
    public R<Customer> detail(@PathVariable("id") String id) {
        return R.data(customerService.get(id));
    }

    /**
     * 收到分配
     * @param customer
     * @return
     */
    @GetMapping(value = "/manualShare")
    public R manualShare(Customer customer) {
        Customer customerOne=customerService.get(customer.getId());
        SysUser sysUser=iSysUserService.get(customer.getUserId());
        if(null==customerOne||null==sysUser){
            return R.fail("业务对象为空！");
        }
        customerOne.setUserId(sysUser.getUserId());
        customerOne.setUserName(sysUser.getName());
        customerOne.setDeptId(sysUser.getDeptId());
        customerOne.setDeptName(sysUser.getDeptName());
        customerOne.setReceiveTime(new Date());
        customerOne.setStatus(CustomerEnum.MY_CUS.getStatus());
        if(customerService.save(customerOne)){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("type","fenpeiNewCus");
            jsonObject.put("msg",SecurityUtils.getLoginUser().getUser().getName()+"-分配新客户给您了");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                    sysUser.getUserId(),jsonObject.toJSONString()
                    );
            CustomerDongtai customerDongtai=new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType("1");
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-手动转给-"+sysUser.getName());
            customerDongtaiService.save(customerDongtai);
            return R.success();
        }
        return R.fail("分配失败");
    }

    /**
     * 批量分配
     * @param customer
     * @return
     */
    @GetMapping(value = "/manualShareBatch")
    public R manualShareBatch(Customer customer) {
        try {
            SysUser sysUser=iSysUserService.get(customer.getUserId());
            for (String s:customer.getIds()){
                Customer customerOne=customerService.get(s);
                if(null==customerOne||null==sysUser){
                    return R.fail("业务对象为空！");
                }
                customerOne.setUserId(sysUser.getUserId());
                customerOne.setUserName(sysUser.getName());
                customerOne.setDeptId(sysUser.getDeptId());
                customerOne.setDeptName(sysUser.getDeptName());
                customerOne.setReceiveTime(new Date());
                customerOne.setStatus(CustomerEnum.MY_CUS.getStatus());
                customerService.save(customerOne);

                CustomerDongtai customerDongtai=new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType("1");
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-手动转给-"+sysUser.getName());
                customerDongtaiService.save(customerDongtai);
            }
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("type","fenpeiNewCus");
            jsonObject.put("msg",SecurityUtils.getLoginUser().getUser().getName()+"-分配新客户给您了");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                    sysUser.getUserId(),
                    jsonObject.toJSONString());
            return R.success();

        }catch (Exception exception){
            return R.fail("分配失败");
        }
    }

    /**
     * 收到分配
     * @param customer
     * @return
     */
    @GetMapping(value = "/myShareCustomer")
    public R myShareCustomer(Customer customer) {
        Customer customerOne=customerService.get(customer.getId());
        SysUser sysUser=iSysUserService.get(customer.getUserId());
        if(null==customerOne||null==sysUser){
            return R.fail("业务对象为空！");
        }
        customerOne.setUserId(sysUser.getUserId());
        customerOne.setUserName(sysUser.getName());
        customerOne.setDeptId(sysUser.getDeptId());
        customerOne.setDeptName(sysUser.getDeptName());
        customerOne.setReceiveTime(new Date());
        customerOne.setStatus(CustomerEnum.MY_CUS.getStatus());
        if(customerService.save(customerOne)){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("type","fenpeiNewCus");
            jsonObject.put("msg",SecurityUtils.getLoginUser().getUser().getName()+"-分配新客户给您了");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                    sysUser.getUserId(),
                    jsonObject.toJSONString());
            CustomerDongtai customerDongtai=new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType("1");
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-手动转给-"+sysUser.getName());
            customerDongtaiService.save(customerDongtai);
            return R.success();
        }
        return R.fail("分配失败");
    }


    /**
     * 新增客户信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:add')")
    @Log(title = "左心房客户推送信息", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated Customer customer) {
//        customer.setLaiyuan("个人");
        if(StringUtils.isEmpty(customer.getPhone())){
            return R.fail("客户手机号不能是空");
        }
        customer.setId(Md5Utils.hash(customer.getPhone()));
        customer.setIsNewRecord();
        customer.setReceiveTime(new Date());
        customer.setOwnType("2");
        customer.setLaiyuanType("2");
        if(StringUtils.isEmpty(customer.getStatus())){
            customer.setStatus("0");
        }
        Customer customer1= customerService.findCustomerByphone(customer.getPhone().trim());
        if(null!=customer1){
            return R.fail("客户已存在，当前客户经理是【"+customer1.getUserName()+"】");
        }
        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType("1");
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-新增客户信息");
        customerDongtaiService.save(customerDongtai);
        return R.status(customerService.save(customer));
    }

    /**
     * 修改左心房客户推送信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:edit')")
    // @Log(title = "左心房客户推送信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated Customer customer) {
        if (!StringUtils.isNull(customer.getIsDail())&&1L==customer.getIsDail()) {
            customer.setDailTime(new Date());
        }
        if("cjkh".equals(customer.getProgress())){
            customer.setIsCj(1);
            customer.setStatus(CustomerEnum.CHENG_JIAO.getStatus());
            customer.setCjTime(new Date());
        }
        if(1==customer.getIsCj()&&!"cjkh".equals(customer.getProgress())){
            customer.setIsCj(0);
            customer.setStatus(CustomerEnum.MY_CUS.getStatus());
        }

        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType("3");
        String cusStatus="-";
        for (CustomerEnum customerEnum:CustomerEnum.values()){
            if(customerEnum.getStatus().equals(customer.getStatus())){
                cusStatus+=customerEnum.getStatusValue();
                break;
            }
        }
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新客户信息"+cusStatus);
        customerDongtaiService.save(customerDongtai);
        return R.status(customerService.save(customer));
    }
    @PostMapping("/updateHeart")
    public R updateHeart(@RequestBody @Validated Customer customer) {
        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType("3");
        String cusStatus="";
        if (2==customer.getIsHeart()){
            cusStatus="标记重点客户";
        }
        else if(1==customer.getIsHeart()){
            cusStatus="取消重点客户";
        }else{
            return R.fail("操作失败");
        }
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-"+cusStatus);
        if (customerService.updateIsHeart(customer)>0){
            customerDongtaiService.save(customerDongtai);
            return R.success();
        }else{
            return R.fail("操作失败");
        }

    }




    /**
     * 删除左心房客户推送信息
     */
    @Log(title = "客户信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(customerService.deleteCustomerByIds(ids));
    }

    /**
     * 获取最大编号
     */
    @GetMapping("/findMaxSort")
    public R findMaxSort() {
        return R.data(customerService.findMaxSort(new Customer()));
    }

    /**
     * 导出房客户推送信息列表
     */
    @Log(title = "客户导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(Customer customer) {

        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setCompanyId(null);
        } else {
            customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<Customer> list = customerService.findList(customer);
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        return util.exportExcel(list, "客户信息导出");
    }
    /**
     * 导出房客户推送信息列表
     */
    @Log(title = "客户导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportMd5")
    public R exportMd5(Customer customer) {


        List<CustomerExpertVo> list = customerService.findAllExportList();
        ExcelUtil<CustomerExpertVo> util = new ExcelUtil<CustomerExpertVo>(CustomerExpertVo.class);
        return util.exportExcel(list, "客户加密导出");
    }

    @Log(title = "客户信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,String status) throws Exception {
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        List<Customer> customerList = util.importExcel(file.getInputStream());
        String message = customerService.importData(customerList,status);
        return AjaxResult.success(message);
    }

    @Log(title = "客户信息修改", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestBody Customer customer) throws Exception {


        // 公海领取  //到我的线索池或者到我的客户
        if(CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())||CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())){
            BusinessSet businessSet=businessSetService.get("index_set");
            if(1==(businessSet.getIsTime())){
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date setTime = sdf.parse(businessSet.getStartTime());
                Date endTime = sdf.parse(businessSet.getEndTime());
                LocalTime now = LocalTime.now();
                // 定义时间段
                LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(),setTime.getSeconds()); // 上午9点
                LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(),endTime.getSeconds()); // 下午5点
                if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
                    customer.setUserId(SecurityUtils.getUserId());
                    customer.setUserName(SecurityUtils.getLoginUser().getUser().getName());
                    customer.setDeptId(SecurityUtils.getDeptId());
                    customer.setDeptName(SecurityUtils.getLoginUser().getUser().getDeptName());
                } else {
                    return R.fail("不在获取公海客户的时间段");
                }
            }
        }


        CustomerDongtai customerDongtai=null;
        for(String id:customer.getIds()){
            customerDongtai=new CustomerDongtai();
            customerDongtai.setCustomerId(id);
            customerDongtai.setType("3");
            if(customer.getStatus().equals(CustomerEnum.GONG_HAI.getStatus())){
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新信息-(转入公海)");
            }
            if(customer.getStatus().equals(CustomerEnum.HEI_MINGDAN.getStatus())){
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新信息-(转入黑名单)");
            }
            if(customer.getStatus().equals(CustomerEnum.YI_FP.getStatus())){
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新信息-(转入线索池)");
            }
            if(customer.getStatus().equals(CustomerEnum.MY_CUS.getStatus())){
                customer.setReceiveTime(new Date());
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新信息-(转入我的客户)");
            }
            customerDongtaiService.save(customerDongtai);
            if(customer.getStatus().equals(CustomerEnum.GONG_HAI.getStatus())||customer.getStatus().equals(CustomerEnum.HEI_MINGDAN.getStatus())){
                CustomerXiezu customerXiezu=new CustomerXiezu();
                customerXiezu.setCustomerId(id);
                customerXiezuService.deleteByCustomerId(customerXiezu);
                customerDongtai=new CustomerDongtai();
                customerDongtai.setCustomerId(id);
                customerDongtai.setType("3");
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-客户到公海-(删除协助人员)");
                customerDongtaiService.save(customerDongtai);
            }

        }

        if(CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())||CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())){
            return customerService.updateGongHaiStatus(customer)>0?R.success():R.fail("操作错误");
        }else{
            return customerService.updateStatus(customer)>0?R.success():R.fail("操作错误");
        }
    }

    @Log(title = "公海领取客户", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStatusGongHai")
    public R updateStatusGongHai(@RequestBody Customer customer) throws Exception {
        // 公海领取  //到我的线索池或者到我的客户
        if(CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())||CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())){
            BusinessSet businessSet=businessSetService.get("index_set");
            if(1==(businessSet.getIsTime())){
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date setTime = sdf.parse(businessSet.getStartTime());
                Date endTime = sdf.parse(businessSet.getEndTime());
                LocalTime now = LocalTime.now();
                // 定义时间段
                LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(),setTime.getSeconds()); // 上午9点
                LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(),endTime.getSeconds()); // 下午5点
                if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
                    customer.setUserId(SecurityUtils.getUserId());
                    customer.setUserName(SecurityUtils.getLoginUser().getUser().getName());
                    customer.setDeptId(SecurityUtils.getDeptId());
                    customer.setDeptName(SecurityUtils.getLoginUser().getUser().getDeptName());
                } else {
                    return R.fail("不在获取公海客户的时间段");
                }
            }
        }
        CustomerDongtai customerDongtai=null;
        for(String id:customer.getIds()){
            customerDongtai=new CustomerDongtai();
            customerDongtai.setCustomerId(id);
            customerDongtai.setType("3");
            if(customer.getStatus().equals(CustomerEnum.YI_FP.getStatus())){
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新信息-(转入线索池)");
            }
            if(customer.getStatus().equals(CustomerEnum.MY_CUS.getStatus())){
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-更新信息-(转入我的客户)");
            }
            customerDongtaiService.save(customerDongtai);
        }

        if(CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus())||CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())){
            return customerService.updateGongHaiStatus(customer)>0?R.success():R.fail("操作错误");
        }else{
            return customerService.updateStatus(customer)>0?R.success():R.fail("操作错误");
        }
    }

    /**
     * 首页查询用户信息
     * @param customer
     * @return
     */
    @Log(title = "首页查询用户信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/findCustomerByPhone")
    public R findCustomerByPhone(Customer customer) {
        Customer customerOne=customerService.findByPhone(customer);
        return R.data(customerOne);
    }

    /**
     * 锁定客户
     * @param customer
     * @return
     */
    @Log(title = "锁定/取消锁客 客户", businessType = BusinessType.SELECT)
    @GetMapping(value = "/lockCustomer")
    public R lockCustomer(Customer customer) {
        CustomerDongtai customerDongtai=new CustomerDongtai();
        if(customer.getIsLock()==1){
            Integer lockCounts=customerService.findLocks(customer);
            BusinessSet businessSet=businessSetService.get("index_set");
            if(lockCounts>=businessSet.getManagerLockNums()){
                return R.fail("锁定客户数量已经到上线："+businessSet.getManagerLockNums());
            }
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType("3");
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-锁定客户");
            customerDongtaiService.save(customerDongtai);
        }else{
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType("3");
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-解锁客户");
            customerDongtaiService.save(customerDongtai);
        }
        return R.status(customerService.lockCustomer(customer));
    }



    /**
     * 导出广告成本
     */
    @Log(title = "导出广告成本", businessType = BusinessType.EXPORT)
    @GetMapping("/exportChengBen")
    public R exportChengBen(Customer customer) {
        List<GuanggaoChengBen> list = customerService.guanggaoChengben(customer);
        ExcelUtil<GuanggaoChengBen> util = new ExcelUtil<GuanggaoChengBen>(GuanggaoChengBen.class);
        return util.exportExcel(list, "广告成本统计");
    }


    /**
     * 统计广告成本
     * @param customer
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/guanggaochengben")
    public R<PageInfo> guanggaochengben(Customer customer, HttpServletRequest request, HttpServletResponse response) {

        customer.setPage(new PageDomain(request, response));

        return R.data(customerService.pageGuanggaoChengben(customer));
    }
    /**
     * 统计广告成本合计
     * @param customer
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/heJiGuanggaochengben")
    public R heJiGuanggaochengben(Customer customer,
            HttpServletRequest request, HttpServletResponse response) {

        customer.setPage(new PageDomain(request, response));

        return R.data(customerService.hejiGuanggaochengben(customer));
    }





    /**
     * 工资统计
     * @param customer
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/yuangonggongzitongji")
    public R yuangonggongzitongji(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        if(!StringUtils.isNotNull(customer.getCreateTime())){
            customer.setCreateTime(new Date());
        }
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.yuangonggongzitongji(customer));
    }


    /**
     * 工资统计导出
     * @param customer
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/exportyuangonggongzitongji")
    public R exportyuangonggongzitongji(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        List<YuanGongGongziVo> list = customerService.yuangonggongzitongji(customer);
        ExcelUtil<YuanGongGongziVo> util = new ExcelUtil<YuanGongGongziVo>(YuanGongGongziVo.class);
        return util.exportExcel(list, "员工工资统计");
    }


    /**
     * 查看客户电话
     * @param customer
     * @return
     */
    @GetMapping("/lookPhone")
    public R lookPhone(Customer customer) {
        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType("3");
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-后台查看客户电话");
        return R.status(customerDongtaiService.save(customerDongtai));
    }

    /**
     * 查看客户电话
     * @param customer
     * @return
     */
    @GetMapping("/lookAppPhone")
    public R lookAppPhone(Customer customer) {
        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType("3");
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-APP查看客户电话");
        return R.status(customerDongtaiService.save(customerDongtai));
    }

    /**
     * testWebSocket

     * @return
     */
    @GetMapping("/testWebSocket")
    public R testWebSocket() {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","fenpeiNewCus");
        jsonObject.put("msg",SecurityUtils.getLoginUser().getUser().getName()+"-分配新客户给您了");
        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_APP,
                SecurityUtils.getUserId(), jsonObject.toJSONString());
        return R.success();
    }

    /**
     * testWebSocket

     * @return
     */
    @GetMapping("/testWebSocketPc")
    public R testWebSocketByPc() {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","fenpeiNewCus");
        jsonObject.put("msg",SecurityUtils.getLoginUser().getUser().getName()+"-分配新客户给您了");
        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                SecurityUtils.getUserId(), jsonObject.toJSONString());
        return R.success();
    }

    @GetMapping("/testWebSocketPc2")
    public R testWebSocketByPc2() {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","xiezuCus");
        jsonObject.put("msg",SecurityUtils.getLoginUser().getUser().getName()+"-分配新客户给您了");
        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                SecurityUtils.getUserId(), jsonObject.toJSONString());
        return R.success();
    }


    /**
     * testWebSocket

     * @return
     */
    @GetMapping("/playCall")
    public R playCall(Customer customer) {
        // 查询用户是否在线
         Session session=
                 WebSocketUsers.getUsers().get(WebSocketUsers.TYPE_APP+SecurityUtils.getLoginUser().getUser().getId());
         // 判断是否在线
         if(null!=session){
             JSONObject jsonObject=new JSONObject();
             jsonObject.put("type","playCall");
             jsonObject.put("phone",customer.getPhone());
             WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_APP,SecurityUtils.getLoginUser().getUser().getId(),
                     jsonObject.toJSONString());
             CustomerDongtai customerDongtai=new CustomerDongtai();
             customerDongtai.setCustomerId(customer.getId());
             customerDongtai.setType("3");
             customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-后台拨打电话");
             customerDongtaiService.save(customerDongtai);
             return R.success("启动成功，请查看手机！");
         }else{
             return R.fail("设备不在线！");
         }

    }

    /**
     * 回传评分推送信息
     */
    @Log(title = "回传评分推送信息", businessType = BusinessType.UPDATE)
    @PostMapping("/clueRate")
    public R clueRate(@RequestBody Customer customer) {
        if (StringUtils.isNotEmpty(customer.getLevel())){
            if("乐数云".equals(customer.getLaiyuan())){
                // 回传
                String return_url = "https://crm.lejiangtang.com/ljt/web/api/ljt/api/callbackClue";
                JSONObject params = new JSONObject();
                params.put("clueId", customer.getClueId());
                String dataType="";
                if ("0".equals(customer.getLevel())){
                    dataType="ONE_STAR";
                }else if ("1".equals(customer.getLevel())){
                    dataType="ONE_STAR";
                }else if ("2".equals(customer.getLevel())){
                    dataType="TWO_STAR";
                }else if ("3".equals(customer.getLevel())){
                    dataType="THREE_STAR";
                }else if ("4".equals(customer.getLevel())){
                    dataType="FOUR_STAR";
                }else if ("5".equals(customer.getLevel())){
                    dataType="FIVE_STAR";
                }
                params.put("dataType", dataType);
                JSONObject result= JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                if (StringUtils.isNotNull(result)){
                    CustomerDongtai customerDongtai=new CustomerDongtai();
                    customerDongtai.setCustomerId(customer.getId());
                    customerDongtai.setType("3");
                    customerDongtai.setContent(customer.getLaiyuan()+"-回传客户评级-"+(result.getString("code").equals(
                            "200")?"成功":"失败"));
                    customerDongtaiService.save(customerDongtai);
                }
            }
            if("融享客".equals(customer.getLaiyuan())){
                // 回传
                String return_url = RongXiangKeAESUtil.HOST +"/crm-report/api/clue/gradeSync";
                JSONObject params = new JSONObject();
                params.put("requestId", UUID.randomUUID());
                params.put("voucherCode",RongXiangKeAESUtil.VOUCHER_CODE);
                JSONObject data=new JSONObject();
                data.put("orderNo", customer.getClueId());
                int grade=0;
                if(StringUtils.isEmpty(customer.getLevel())){
                    grade=0;
                }else if ("0".equals(customer.getLevel())){
                    grade=0;
                }else if ("1".equals(customer.getLevel())){
                    grade=10;
                }else if ("2".equals(customer.getLevel())){
                    grade=20;
                }else if ("3".equals(customer.getLevel())){
                    grade=30;
                }else if ("4".equals(customer.getLevel())){
                    grade=40;
                }else if ("5".equals(customer.getLevel())){
                    grade=50;
                }
                data.put("grade",grade);
                params.put("data",RongXiangKeAESUtil.encrypt(data.toJSONString(),RongXiangKeAESUtil.KEY));
                JSONObject result= JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                if (StringUtils.isNotNull(result)){
                    CustomerDongtai customerDongtai=new CustomerDongtai();
                    customerDongtai.setCustomerId(customer.getId());
                    customerDongtai.setType("3");
                    customerDongtai.setContent(customer.getLaiyuan()+"-回传客户评级-"+(result.getString("msg").equals(
                            "success")?"成功":"失败"));
                    customerDongtaiService.save(customerDongtai);
                }
            }
            if("融薪花".equals(customer.getLaiyuan())){
                // 回传
                String return_url = RongXiangKeAESUtil.HOST +"/crm-report/api/clue/gradeSync";
                JSONObject params = new JSONObject();
                params.put("requestId", UUID.randomUUID());
                params.put("voucherCode", customer.getClueId());
                JSONObject data=new JSONObject();
                data.put("orderNo", customer.getClueId());
                data.put("grade", customer.getLevel());
                params.put("data",RongXiangKeAESUtil.encrypt(data.toJSONString(),RongXiangKeAESUtil.KEY));
                JSONObject result= JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                if (StringUtils.isNotNull(result)){
                    CustomerDongtai customerDongtai=new CustomerDongtai();
                    customerDongtai.setCustomerId(customer.getId());
                    customerDongtai.setType("3");
                    customerDongtai.setContent(customer.getLaiyuan()+"-回传客户评级-"+(result.getString("msg").equals(
                            "success")?"成功":"失败"));
                    customerDongtaiService.save(customerDongtai);
                }
            }

        }
        return R.status(customerService.save(customer));
    }


    public static void main(String[] args) throws ParseException {
        System.out.println(md5Lower("18367479183"));
    }


    public static String md5Lower(String plainText) {
        String md5 = null;
        if (null != plainText && !"".equals(plainText)) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(plainText.getBytes("UTF-8"));
                md5 =  new BigInteger(1, md.digest()).toString(16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return md5;
    }





}
